package com.shushan.mixedexam.oralcalculation;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shushan.base.BaseFragment;
import com.shushan.base.Constants;
import com.shushan.mixedexam.oralcalculation.bean.OralCalculateExerciseBean;
import com.shushan.shushanbao.R;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @ClassName: OralCalculationExamFragment
 * @Desciption: //口算试题fragment
 * @author: zhangshihao
 * @date: 2018-06-20
 */
public class OralCalculationExamFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = OralCalculationExamFragment.class.getSimpleName();
    private static final int ANSWER_TEXT_MAX_LENGTH = 6;

    private LinearLayout layout0, layout1, layout2, layout3, layout4, layout5,
            layout6, layout7, layout8, layout9, urgentLayout, deleteLayout;
    private TextView tvQuestion;
    private LinearLayout llKeyBoardContainer;
    private TextView tvRightAnswer;
    private LinearLayout llNcContainer;
    private LinearLayout llFcContainer;
    private TextView fz1, fm1, ys1, fz2, fm2;
    private View line1, line2, answerLine;
    private RelativeLayout rlAnswerFz, rlAnswerFm;
    private EditText etAnswerFz, etAnswerFm;

    private int answerLength = 0;//正确答案长度
    private String rightAnswer = "";//正确答案
    private int examIndex = 0;
    private boolean fromRecord;
    private boolean focusedFz = false;
    private boolean isFzComplete = false;
    private boolean isFmComplete = false;

    private boolean isOnlyDisplay = false;

    private OralCalculateExerciseBean exerciseBean;

    private OnAnswerCompleteListener onAnswerCompleteListener;
    private EditText etAnswer;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!isOnlyDisplay && isAnswerComplete(s.toString())) {
                onAnswerCompleteListener.onAnswerComplete(examIndex, s.toString().equals(rightAnswer), s.toString());
            }
        }
    };
    private TextWatcher fzWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!isOnlyDisplay && isFzComplete(s.toString()) && isFmComplete) {
                boolean isRight = false;
                if(TextUtils.isEmpty(etAnswerFm.getText().toString())){
                    if((!TextUtils.isEmpty(etAnswerFz.getText().toString()) && etAnswerFz.getText().toString().equals(String.valueOf(exerciseBean.fz))) &&
                            "0".equals(String.valueOf(exerciseBean.fm))){
                        isRight = true;
                    }
                }else{
                    if((!TextUtils.isEmpty(etAnswerFz.getText().toString()) && etAnswerFz.getText().toString().equals(String.valueOf(exerciseBean.fz))) &&
                            etAnswerFm.getText().toString().equals(String.valueOf(exerciseBean.fm))){
                        isRight = true;
                    }
                }
                if(!TextUtils.isEmpty(etAnswerFm.getText().toString())) {
                    onAnswerCompleteListener.onAnswerComplete(examIndex, isRight, getFcAnswerStr(s.toString(), etAnswerFm.getText().toString()));
                }else{
                    onAnswerCompleteListener.onAnswerComplete(examIndex, isRight, getFcAnswerStr(s.toString(), "0"));
                }
            }
        }
    };
    private TextWatcher fmWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!isOnlyDisplay && isFmComplete(s.toString()) && isFzComplete) {
                boolean isRight = false;
                if ((!TextUtils.isEmpty(etAnswerFz.getText().toString()) && etAnswerFz.getText().toString().equals(String.valueOf(exerciseBean.fz))) &&
                        (!TextUtils.isEmpty(etAnswerFm.getText().toString()) && etAnswerFm.getText().toString().equals(String.valueOf(exerciseBean.fm)))) {
                    isRight = true;
                }
                onAnswerCompleteListener.onAnswerComplete(examIndex, isRight, getFcAnswerStr(etAnswerFz.getText().toString(),s.toString()));
            }
        }
    };

    private String getFcAnswerStr(String fz,String fm){
        StringBuffer sb = new StringBuffer();
        sb.append("{\"fz\":")
                .append(fz)
                .append(",\"fm\":")
                .append(fm)
                .append("}");
        return sb.toString();
    }

    private boolean isAnswerComplete(String answer) {
        if (answer.equals(rightAnswer)) {
            return true;
        }
        if (answer.length() == answerLength) {
            return true;
        }
        return false;
    }

    private boolean isFzComplete(String answer) {
        if (answer.equals(String.valueOf(exerciseBean.fz))) {
            isFzComplete = true;
            etAnswerFm.performClick();
            return true;
        }
        if (answer.length() == String.valueOf(exerciseBean.fz).length()) {
            isFzComplete = true;
            etAnswerFm.performClick();
            return true;
        }
        isFzComplete = false;
        return false;
    }

    private boolean isFmComplete(String answer) {
        if (answer.equals(String.valueOf(exerciseBean.fm))) {
            isFmComplete = true;
            etAnswerFz.performClick();
            return true;
        }
        if (answer.length() == String.valueOf(exerciseBean.fm).length()) {
            isFmComplete = true;
            etAnswerFz.performClick();
            return true;
        }
        isFmComplete = false;
        return false;
    }

    public static OralCalculationExamFragment newInstance(boolean isOnlyDisplay, OnAnswerCompleteListener listener, int examIndex, OralCalculateExerciseBean exerciseBean, boolean fromRecord) {
        OralCalculationExamFragment examFragment = new OralCalculationExamFragment();
        examFragment.setOnAnswerCompleteListener(listener);
        examFragment.setExamIndex(examIndex);
        examFragment.setExerciseBean(exerciseBean);
        examFragment.setOnlyDisplay(isOnlyDisplay);
        examFragment.setFromRecord(fromRecord);

        return examFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_oral_calculate_exam, null, false);

        initView(view);

        setData();

        return view;
    }

    private void setData() {
        if (exerciseBean == null) {
            return;
        }

        if (exerciseBean.type == 1) {
            llNcContainer.setVisibility(View.GONE);
            llFcContainer.setVisibility(View.VISIBLE);
            fz1.setText(String.valueOf(exerciseBean.fz1));
            if (exerciseBean.fm1 == 0 || exerciseBean.fm1 == 1) {
                line1.setVisibility(View.GONE);
                fm1.setVisibility(View.GONE);
            } else {
                fm1.setText(String.valueOf(exerciseBean.fm1));
            }
            ys1.setText(exerciseBean.ys1);
            fz2.setText(String.valueOf(exerciseBean.fz2));
            if (exerciseBean.fm2 == 0 || exerciseBean.fm2 == 1) {
                line2.setVisibility(View.GONE);
                fm2.setVisibility(View.GONE);
            } else {
                fm2.setText(String.valueOf(exerciseBean.fm2));
            }
            if (exerciseBean.fm == 0 || exerciseBean.fm == 1) {
                rlAnswerFm.setVisibility(View.GONE);
                answerLine.setVisibility(View.GONE);
                etAnswerFz.performClick();
                focusedFz = true;
                isFmComplete = true;
            }
        } else {
            llNcContainer.setVisibility(View.VISIBLE);
            llFcContainer.setVisibility(View.GONE);
            tvRightAnswer.setText(exerciseBean.answer);
            tvQuestion.setText(exerciseBean.questions);
            answerLength = exerciseBean.answer.length();
            rightAnswer = exerciseBean.answer;
        }

        if (isOnlyDisplay) {
            if(exerciseBean.type == 0) {
                if (!fromRecord) {
                    etAnswer.setText(exerciseBean.my_answer);
                } else {
                    etAnswer.setText(exerciseBean.my_answer_id);
                }
            }else{
                rlAnswerFz.setBackgroundResource(R.drawable.bg_more_thin_blue_stroke_blue_radius_7);
                rlAnswerFm.setBackgroundResource(R.drawable.bg_more_thin_blue_stroke_blue_radius_7);
                try {
                    String answer = "";
                    if (!fromRecord) {
                        answer = exerciseBean.my_answer;
                    } else {
                        answer = exerciseBean.my_answer_id;
                    }
                    JSONObject fcObj = new JSONObject(answer);
                    int fz = fcObj.optInt("fz",0);
                    int fm = fcObj.optInt("fm",0);
                    etAnswerFz.setText(fz+"");
                    if(fm==0 || fm == 1){
                        rlAnswerFm.setVisibility(View.GONE);
                        answerLine.setVisibility(View.GONE);
                    }else{
                        etAnswerFm.setText(fm+"");
                    }
                }catch (JSONException je){
                    je.printStackTrace();
                }
            }
        }
    }

    private void initView(View view) {
        layout0 = view.findViewById(R.id.pin_lock_screen_0_layout);
        layout0.setOnClickListener(this);
        layout1 = view.findViewById(R.id.pin_lock_screen_1_layout);
        layout1.setOnClickListener(this);
        layout2 = view.findViewById(R.id.pin_lock_screen_2_layout);
        layout2.setOnClickListener(this);
        layout3 = view.findViewById(R.id.pin_lock_screen_3_layout);
        layout3.setOnClickListener(this);
        layout4 = view.findViewById(R.id.pin_lock_screen_4_layout);
        layout4.setOnClickListener(this);
        layout5 = view.findViewById(R.id.pin_lock_screen_5_layout);
        layout5.setOnClickListener(this);
        layout6 = view.findViewById(R.id.pin_lock_screen_6_layout);
        layout6.setOnClickListener(this);
        layout7 = view.findViewById(R.id.pin_lock_screen_7_layout);
        layout7.setOnClickListener(this);
        layout8 = view.findViewById(R.id.pin_lock_screen_8_layout);
        layout8.setOnClickListener(this);
        layout9 = view.findViewById(R.id.pin_lock_screen_9_layout);
        layout9.setOnClickListener(this);
        deleteLayout = view.findViewById(R.id.pin_lock_screen_delete_layout);
        deleteLayout.setOnClickListener(this);
        urgentLayout = view.findViewById(R.id.pin_lock_screen_urgent_layout);
        urgentLayout.setOnClickListener(this);
        etAnswer = view.findViewById(R.id.et_answer);
        etAnswer.addTextChangedListener(textWatcher);
        tvQuestion = view.findViewById(R.id.tv_question);
        llKeyBoardContainer = view.findViewById(R.id.ll_keyboard_container);
        llNcContainer = view.findViewById(R.id.ll_normal_calculate_container);
        llFcContainer = view.findViewById(R.id.ll_fc_container);
        fz1 = view.findViewById(R.id.tv_son_1);
        line1 = view.findViewById(R.id.view_fraction_1);
        fm1 = view.findViewById(R.id.tv_mom_1);
        ys1 = view.findViewById(R.id.tv_calculate_symbol);
        fz2 = view.findViewById(R.id.tv_son_2);
        line2 = view.findViewById(R.id.view_fraction_2);
        fm2 = view.findViewById(R.id.tv_mom_2);
        answerLine = view.findViewById(R.id.view_fraction_answer);
        rlAnswerFz = view.findViewById(R.id.rl_answer_son_container);
        rlAnswerFm = view.findViewById(R.id.rl_answer_mom_container);
        etAnswerFz = view.findViewById(R.id.et_answer_son);
        etAnswerFm = view.findViewById(R.id.et_answer_mom);
        etAnswerFz.setOnClickListener(this);
        etAnswerFm.setOnClickListener(this);
        etAnswerFz.addTextChangedListener(fzWatcher);
        etAnswerFm.addTextChangedListener(fmWatcher);


        if (isOnlyDisplay) {
            llKeyBoardContainer.setVisibility(View.GONE);
        }
        tvRightAnswer = view.findViewById(R.id.tv_right_selector);
        if (!Constants.isForEditors) {
            tvRightAnswer.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pin_lock_screen_0_layout:
                addPwdText(0);
                break;
            case R.id.pin_lock_screen_1_layout:
                addPwdText(1);
                break;
            case R.id.pin_lock_screen_2_layout:
                addPwdText(2);
                break;
            case R.id.pin_lock_screen_3_layout:
                addPwdText(3);
                break;
            case R.id.pin_lock_screen_4_layout:
                addPwdText(4);
                break;
            case R.id.pin_lock_screen_5_layout:
                addPwdText(5);
                break;
            case R.id.pin_lock_screen_6_layout:
                addPwdText(6);
                break;
            case R.id.pin_lock_screen_7_layout:
                addPwdText(7);
                break;
            case R.id.pin_lock_screen_8_layout:
                addPwdText(8);
                break;
            case R.id.pin_lock_screen_9_layout:
                addPwdText(9);
                break;
            case R.id.pin_lock_screen_delete_layout:
                addPwdText(-1);
                break;
            case R.id.pin_lock_screen_urgent_layout://输入.
                addPwdText(-2);
                break;
            case R.id.et_answer_son:
                focusedFz = true;
                rlAnswerFz.setBackgroundResource(R.drawable.bg_more_thin_blue_stroke_blue_radius_7);
                rlAnswerFm.setBackgroundResource(R.drawable.bg_gray_stroke_gray_radius_7);
                break;
            case R.id.et_answer_mom:
                focusedFz = false;
                rlAnswerFm.setBackgroundResource(R.drawable.bg_more_thin_blue_stroke_blue_radius_7);
                rlAnswerFz.setBackgroundResource(R.drawable.bg_gray_stroke_gray_radius_7);
                break;
        }
    }

    private void addPwdText(int num) {
        Log.i(TAG, "addPwdText num=" + num);
        if (exerciseBean.type == 0) {
            String answer = etAnswer.getText().toString();
            if (num >= 0 && answer.length() > ANSWER_TEXT_MAX_LENGTH) {
                return;
            }

            if (num >= 0) {
                etAnswer.setText(answer + num);
            } else {
                if (TextUtils.isEmpty(answer)) {
                    return;
                }
                if (num == -1) {
                    etAnswer.setText(answer.substring(0, answer.length() - 1));
                } else if (num == -2) {
                    etAnswer.setText(answer + ".");
                }

            }
        } else {
            String answer = "";
            if (focusedFz) {
                answer = etAnswerFz.getText().toString();
            } else {
                answer = etAnswerFm.getText().toString();
            }
            if (num > 0 && answer.length() > (ANSWER_TEXT_MAX_LENGTH - 3)) {
                return;
            }

            if (num >= 0) {
                if (focusedFz) {
                    etAnswerFz.setText(answer + num);
                } else {
                    etAnswerFm.setText(answer + num);
                }
            } else {
                if (TextUtils.isEmpty(answer)) {
                    return;
                }
                if (num == -1) {
                    if (focusedFz) {
                        etAnswerFz.setText(answer.substring(0, answer.length() - 1));
                    } else {
                        etAnswerFm.setText(answer.substring(0, answer.length() - 1));
                    }
                } else if (num == -2) {
                    if (focusedFz) {
                        etAnswerFz.setText(answer + ".");
                    } else {
                        etAnswerFm.setText(answer + ".");
                    }
                }
            }
        }
    }

    public void setOnAnswerCompleteListener(OnAnswerCompleteListener onAnswerCompleteListener) {
        this.onAnswerCompleteListener = onAnswerCompleteListener;
    }

    public void setExamIndex(int examIndex) {
        this.examIndex = examIndex;
    }

    public OralCalculateExerciseBean getExerciseBean() {
        return exerciseBean;
    }

    public void setExerciseBean(OralCalculateExerciseBean exerciseBean) {
        this.exerciseBean = exerciseBean;
    }

    public void setOnlyDisplay(boolean onlyDisplay) {
        isOnlyDisplay = onlyDisplay;
    }

    public void setFromRecord(boolean fromRecord) {
        this.fromRecord = fromRecord;
    }
}
